const app = getApp()
const { get } = require('../../utils/request')

Page({
  data: {
    hasLogin: false,
    searchKeyword: '',
    userStats: null,
    recommendRecipes: {
      breakfast: [],
      lunch: [],
      dinner: []
    },
    nutritionArticles: [],
    banners: [
      {
        id: 1,
        imageUrl: '/images/banner.jpg'
      },
      {
        id: 2,
        imageUrl: '/images/banner.jpg'
      },
      {
        id: 3,
        imageUrl: '/images/banner.jpg'
      }
    ],
    currentDate: '',
    healthData: {
      bmi: 0,
    },
    bmiStatus: {
      class: 'normal',
      text: '',
      suggestion: ''
    },
    nutritionData: {
      calories: 0,
      protein: 0,
      carbs: 0,
      fat: 0
    },
    nutritionGoals: {
      calories: 2000,
      protein: 60,
      carbs: 250,
      fat: 70
    },
    healthSuggestions: []
  },

  onLoad() {
    this.setData({
      hasLogin: app.globalData.hasLogin,
      currentDate: this.formatDate(new Date())
    })
    
    if (app.globalData.hasLogin) {
      this.getRecommendRecipes()
      this.getHealthAnalysis()
    }
  },

  onShow() {
    // 检查登录状态是否发生变化
    if (this.data.hasLogin !== app.globalData.hasLogin) {
      this.setData({
        hasLogin: app.globalData.hasLogin
      })
      if (app.globalData.hasLogin) {
        this.getRecommendRecipes()
        this.getHealthAnalysis()
      }
    }
  },

  formatDate(date) {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    return `${year}年${month}月${day}日`
  },

  async getRecommendRecipes() {
    try {
      wx.showLoading({
        title: '加载中...'
      })

      const result = await get('/recipes/recommend')
      
      this.setData({
        userStats: result.userStats,
        recommendRecipes: result.recipes
      })

    } catch (error) {
      console.error('获取推荐食谱失败:', error)
      wx.showToast({
        title: '获取推荐失败',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  async getNutritionArticles() {
    try {
      const articles = await get('/articles/nutrition')
      this.setData({
        nutritionArticles: articles
      })
    } catch (error) {
      console.error('获取营养知识文章失败:', error)
    }
  },

  async getHealthAnalysis() {
    try {
      wx.showLoading({
        title: '加载中...'
      })

      const result = await get('/users/health-analysis')
      console.log(result,'ss')
      // 计算BMI状态
      const bmiStatus = this.calculateBMIStatus(result.bmi)
      
     

      this.setData({
        healthData: result,
        bmiStatus,
       
      })

    } catch (error) {
      console.error('获取健康分析失败:', error)
      wx.showToast({
        title: '获取分析失败',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  calculateBMIStatus(bmi) {
    if (bmi < 18.5) {
      return {
        class: 'warning',
        text: '体重偏轻',
        suggestion: '建议适当增加营养摄入，注意补充蛋白质'
      }
    } else if (bmi >= 18.5 && bmi < 24) {
      return {
        class: 'normal',
        text: '体重正常',
        suggestion: '请继续保持健康的生活方式'
      }
    } else if (bmi >= 24 && bmi < 28) {
      return {
        class: 'warning',
        text: '超重',
        suggestion: '建议控制饮食，增加运动量'
      }
    } else {
      return {
        class: 'danger',
        text: '肥胖',
        suggestion: '建议咨询医生，制定科学的减重计划'
      }
    }
  },

  navigateToFeature(e) {
    const feature = e.currentTarget.dataset.feature;
    
    switch (feature) {
      case 'recipe':
        wx.navigateTo({
          url: '/pages/recipe/recommend'
        });
        break;
      case 'nutrition':
        wx.navigateTo({
          url: '/pages/food/selector'
        });
        break;
      case 'plan':
        wx.navigateTo({
          url: '/pages/plan/index'
        });
        break;
      case 'compare':
        wx.navigateTo({
          url: '/pages/food/compare'
        });
        break;
      case 'bmi':
        wx.navigateTo({
          url: '/pages/health/bmi'
        });
        break;
      case 'community':
        wx.switchTab({
          url: '/pages/community/index'
        });
        break;
    }
  },

  viewRecipeDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/recipe/detail?id=${id}`
    })
  },

  viewMore(e) {
    const type = e.currentTarget.dataset.type
    wx.navigateTo({
      url: `/pages/recipe/list?category=${type}`
    })
  },

  viewArticle(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/nutrition/article?id=${id}`
    })
  },

  navigateToLogin() {
    wx.navigateTo({
      url: '/pages/login/login'
    })
  },

  onPullDownRefresh() {
    if (app.globalData.hasLogin) {
      this.getRecommendRecipes().then(() => {
        this.getHealthAnalysis().then(() => {
          wx.stopPullDownRefresh()
        })
      })
    } else {
      wx.stopPullDownRefresh()
    }
  },

  // 处理搜索输入
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    })
  },

  // 处理搜索确认
  onSearchConfirm() {
    const { searchKeyword } = this.data
    wx.navigateTo({
      url: `/pages/food/selector?keyword=${encodeURIComponent(searchKeyword)}`
    })
  }
}) 